using UnityEngine;
using UnityEngine.UI;

[AddComponentMenu("YUI/YImage")]
public class YImage : Image
{
    [SerializeField] private string m_spriteName;

    private int m_LoadWebImageFailCount = 0;

    public string spriteName
    {
        get => m_spriteName;
        set
        {
            if (m_spriteName == value) return;

            if (WebImageManager.IsFromWeb(m_spriteName))
            {
                WebImageManager.Instance.RemoveLoadWebImageHandler(this, m_spriteName, LoadWebImageSuccess, LoadWebImageFail);
            }

            m_spriteName = value;

            if (WebImageManager.IsFromWeb(value))
            {
                WebImageManager.Instance.AddLoadWebImageHandler(this, value, LoadWebImageSuccess, LoadWebImageFail);
            }
        } 
    }

    private void ApplyTexture(Texture2D texture)
    {
        if (texture != null)
        {
            sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height),
                new Vector2(0.5f, 0.5f));
        }
    }

    private void LoadWebImageSuccess(Texture2D texture, string imageUrl)
    {
        if (spriteName == imageUrl && texture != null)
        {
            ApplyTexture(texture);
        }
    }

    private void LoadWebImageFail(string imageUrl)
    {
        m_LoadWebImageFailCount++;
        Debug.LogWarning($"----------YImageWrap WebRequestFailure url:{imageUrl},count:{m_LoadWebImageFailCount}");
    }

    new
    void OnDestroy()
    {
        if (WebImageManager.IsFromWeb(m_spriteName))
        {
            WebImageManager.Instance.RemoveLoadWebImageHandler(this, m_spriteName, LoadWebImageSuccess, LoadWebImageFail);
        }
    }
}
